package com.example.cloudzuul.web;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

//@Component
public class TokenFilter extends ZuulFilter {
    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() throws ZuulException {
        // 扩展: ThreadLocal 本地线程变量
        // RequestContext 上下文
        RequestContext context = RequestContext.getCurrentContext();
        // 获取Http请求对象
        HttpServletRequest request = context.getRequest();
        String token = request.getParameter("token");
        //
        if(token == null || checkToken(token, request) == false){
            // 阻止访问目录表资源
            context.setSendZuulResponse(false);
            context.setResponseStatusCode(400);
            context.setResponseBody("{\"code\":0,\"msg\":\"not token\"}");
        }
        return null;
    }

    // 使用令牌算法验证令牌
    public boolean checkToken(String token, HttpServletRequest request){
        return true;
    }
}
